/*
 * Copyright 1999-2018 Alibaba Group Holding Ltd.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.alibaba.csp.sentinel.slots.block.flow.controller;

import java.util.concurrent.atomic.AtomicLong;

import com.alibaba.csp.sentinel.slots.block.flow.TrafficShapingController;

import com.alibaba.csp.sentinel.util.TimeUtil;
import com.alibaba.csp.sentinel.node.Node;

/**
 * @author jialiang.linjl
 */
public class RateLimiterController implements TrafficShapingController {

    private final int maxQueueingTimeMs;
    private final double count;

    private final AtomicLong latestPassedTime = new AtomicLong(-1);

    public RateLimiterController(int timeOut, double count) {
        this.maxQueueingTimeMs = timeOut;
        this.count = count;
    }

    @Override
    public boolean canPass(Node node, int acquireCount) {
        return canPass(node, acquireCount, false);
    }

    @Override
    public boolean canPass(Node node, int acquireCount, boolean prioritized) {
        // Pass when acquire count is less or equal than 0.
        if (acquireCount <= 0) {//当前申请流量小于等0
            return true;//直接返回校验通过
        }
        // Reject when count is less or equal than 0.
        // Otherwise,the costTime will be max of long and waitTime will overflow in some cases.
        if (count <= 0) {//配置规则中配置的单机阈值小于等于0
            return false;//直接返回校验失败
        }//获取当前时间
        long currentTime = TimeUtil.currentTimeMillis();
        // Calculate the interval between every two requests. 计算出斜率，也就是两个请求之间的间隔时间，是匀速的从漏桶中漏出。
        long costTime = Math.round(1.0 * (acquireCount) / count * 1000);
        // Expected pass time of this request. 计算出当前期望流出的时间。
        long expectedTime = costTime + latestPassedTime.get();
        if (expectedTime <= currentTime) {//判断期望流出的时间比当前时间少.
            // Contention may exist here, but it's okay.
            //这里存在并发问题，如果期望时间小于当前时间的话，这一时候所有的请求都会通过
            latestPassedTime.set(currentTime);//记录最近请求通过的时间
            return true;//直接返回校验失败
        } else {//期望时间比当前时间大，需要等待一段时间，才能流出。
            // Calculate the time to wait. 计算出需要等待的时间。
            long waitTime = costTime + latestPassedTime.get() - TimeUtil.currentTimeMillis();
            if (waitTime > maxQueueingTimeMs) {//判断等待时间 大于 配置的超时时间
                return false; //直接返回校验失败
            } else {//加两个请求之间的间隔时间。 这是一个原子操作，没有加锁，所以也不会出现并发问题。
                long oldTime = latestPassedTime.addAndGet(costTime);
                try {//通过 期望通过的时间 减去 当前时间，计算出需要等待的时间
                    waitTime = oldTime - TimeUtil.currentTimeMillis();
                    if (waitTime > maxQueueingTimeMs) {//再次判断等待时间是否 大于 配置的超时时间
                        latestPassedTime.addAndGet(-costTime);//需要还原时间，因为当前请求没有通过，
                        return false;//直接返回校验失败
                    }
                    // in race condition waitTime may <= 0
                    if (waitTime > 0) {//等待时间 大于0
                        Thread.sleep(waitTime);//休眠对应的时间
                    }
                    return true;//返回校验通过
                } catch (InterruptedException e) {
                }
            }
        }
        return false; //抛出异常，就会直接返回校验失败
    }

}
